import { requireAuth } from '~/server/utils/auth'
import CommentService from '~/server/database/services/commentService'

export default defineEventHandler(async (event) => {
  try {
    // 验证用户身份
    const user = await requireAuth(event)
    
    const commentId = parseInt(getRouterParam(event, 'id') || '0')
    const body = await readBody(event)
    const { content } = body

    if (!commentId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '评论ID不能为空' }
      })
    }

    if (!content) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '评论内容不能为空' }
      })
    }

    // 检查评论是否存在
    const existingComment = await CommentService.getCommentById(commentId)
    if (!existingComment) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Not Found',
        data: { message: '评论不存在' }
      })
    }

    // 检查权限（只有作者可以编辑）
    if (existingComment.authorId !== user.id) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Forbidden',
        data: { message: '没有权限编辑此评论' }
      })
    }

    // 更新评论
    const updatedComment = await CommentService.updateComment(commentId, {
      content: content.trim()
    })

    return {
      success: true,
      data: updatedComment,
      message: '评论更新成功'
    }
  } catch (error: unknown) {
    console.error('更新评论失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '更新评论失败' }
    })
  }
})
